package cn.dcw.pethome.basic.interceptor;

import cn.dcw.pethome.org.domain.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component//将这个类的对象交给spring管理
public class LoginInterceptor implements HandlerInterceptor{

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        //1.获取请求头中的token
        String token = request.getHeader("token");
        if(!StringUtils.isEmpty(token)){
            //根据token获取redis中的对象
            Object loginInfo = redisTemplate.opsForValue().get(token);
            //对用户信息进行判断
            if(loginInfo!=null){//不为null，说明redis中的对象还没过期，给予放行
                //防止客户在操作过程中，对象时间到期，客户每次发送请求后，将对象的有效时间更新为30分钟
                redisTemplate.opsForValue().set(token, loginInfo, 30, TimeUnit.MINUTES);
                return true;//放行
            }else{//拦截，跳转到登入界面
                //2 权限拦截 //@TODO
                //都是登录是吧返回一个错误 {“success”:false,"message":"noLogin"}，让前端条页面
                response.setCharacterEncoding("utf-8");
                response.setContentType("application/json; charset=UTF-8");//返回json格式
                PrintWriter writer = response.getWriter();
                // 在外面写好在拷贝进去
                writer.write("{\"success\":false,\"message\":\"noLogin\"}");
                writer.close();
                return false;//拦截
            }
        }
        return false;//拦截
    }
}
